<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>首页</title>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/static/layui/css/layui.css">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/static/layui/css/modules/layer/default/layer.css">
    <script src="${pageContext.request.contextPath}/static/layui/layui.js"></script>
    <script src="${pageContext.request.contextPath}/static/jquery-3.5.1.min.js"></script>
    <script src="${pageContext.request.contextPath}/static/layer/layer.js"></script>
    <style type="text/css">
        .workBtn{
            color: white;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            font-size: xx-large;
            border: 0;
            box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19);
        }
        .workBtn:hover {
            box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19);
        }
        .workBtn i{
            font-size: 80px;
            color: white;
        }
    </style>
</head>
<body style="background-color: #f4f4f4;">
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
    <legend><span style="font-size: xx-large;font-weight: bold;"> 工作区</span></legend>
</fieldset>
<div class="layui-container" style="padding: 30px;">
    <div class="layui-row layui-col-space30" style="margin-bottom: 5vh;">
        <div class="layui-col-md12">
            <div id="time" style="text-align: center;font-size: xx-large;"></div>
        </div>
    </div>
    <form class="layui-row" style="margin-bottom: 5vh;">
        <label class="layui-col-md4 layui-col-md-offset3">
            <input id="account" type="text" name="title" autocomplete="off" placeholder="用户账号" class="layui-input">
        </label>
        <div class="layui-col-md2">
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </form>
    <div class="layui-row layui-col-space30">
        <button type="button" class="layui-col-md3 layui-col-md-offset2 workBtn layui-btn-warm" onclick="borrowBook()">
            <i class="layui-icon layui-icon-read"></i>
            订阅
        </button>
        <button type="button" class="layui-col-md3 layui-col-md-offset2 workBtn layui-btn-checked" onclick="returnBook()">
            <i class="layui-icon layui-icon-log"></i>
            归还/续订
        </button>
    </div>
</div>
</body>
<script type="text/html" id="borrowBar">
    <a class="layui-btn layui-btn-xs" lay-event="borrowBook">借阅</a>
</script>
<script type="text/html" id="returnBar">
    <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="renewBook">续订</a>
    <a class="layui-btn layui-btn-xs" lay-event="returnBook">归还</a>
</script>
<script type="text/html" id="renewBar">
</script>
<script>
    layui.use("table",function (){
        var table = layui.table;

        $("#borrow-bookSerialNumber").on("input",function(e){
            console.log(e.delegateTarget.value);
            borrowBookTableIns.reload({
                where:{
                    "serialNumber": e.delegateTarget.value
                }
            })
        });

        var borrowBookTableIns = table.render({
            elem: '#borrowBookTable'
            ,url:'${pageContext.request.contextPath}/book/getBooksBySerialNumber.do'
            ,where: {
                "serialNumber": $("#borrow-bookSerialNumber").val()
            }
            ,height: 300
            ,cols: [[
                {field:'id',title: 'ID',hide: true}
                ,{field:'title',width: 180, title: '书籍名'}
                ,{field:'serialNumber',width: 120, title: '图书编号'}
                ,{field:'press',width: 135, title: '出版社'}
                ,{field:'author',width: 135,title: '作者'}
                ,{title: '操作',width: 75,fixed:'right', toolbar: '#borrowBar'}
            ]]
        });

        var returnBookTableIns = table.render({
            elem: '#returnBookTable'
            ,url:'${pageContext.request.contextPath}/borrow/getBorrowByAccount.do'
            ,where: {
                "account": $("#account").val()
            }
            ,height: 250
            ,cols: [[
                {field:'id',title: 'ID',hide: true}
                ,{field:'title', title: '书籍名'}
                ,{field:'borrowDate', title: '借书日期',width:110}
                ,{field:'borrowTime', title: '借书时间',width:90}
                ,{field:'status',title: '是否逾期',width:90, templet: function(d){
                        let now = new Date();
                        let borrowDate = new Date(d.borrowDate.replace(/-/g,"/"));
                        let borrowed = now.getTime()-borrowDate.getTime();
                        let days = Math.floor(borrowed / (24 * 3600 * 1000));
                        let timeout = days-d.borrowTime;

                        console.log(days+"-"+d.borrowTime+"="+timeout);

                        if(timeout > 0){
                            return '逾期'+timeout+'天';
                        }else {
                            return '无逾期';
                        }
                    }}
                ,{title: '操作',width: 125, toolbar: '#returnBar'}
            ]]
        });

        table.on('tool(borrowBookTable)', function(obj){
            var data = obj.data;
            switch(obj.event){
                case 'borrowBook':
                    var borrowTimeLimit = $("#borrow-borrowTimeLimit").val();
                    var borrowBookLimit = $("#borrow-borrowBookLimit").val();
                    var borrowBooks = $("#borrow-borrowBooks").val();
                    if(borrowBooks+1 <= borrowBookLimit){
                        layer.prompt({
                            formType: 0,
                            value: borrowTimeLimit,
                            title: '借阅天数',
                        }, function(value, index, elem){
                            if(value <= borrowTimeLimit*1){
                                $.ajax({
                                    url:"${pageContext.request.contextPath}/borrow/borrowBook.do",
                                    data:{
                                        "userId" : $("#borrow-userId").val(),
                                        "bookId" : data.id,
                                        "borrowTime" : value
                                    },
                                    type:"post",
                                    dataType:"json",
                                    success:function (n){
                                        if(n.success){
                                            layer.msg("借阅成功（用户账号："+$("#borrow-account").val()+"，图书名："+data.title+"）");
                                            $("#borrow-borrowBooks").val(borrowBooks*1+1);
                                            layer.close(index);
                                        }else {
                                            layer.msg("借阅失败（"+n.msg+"）");
                                        }
                                    }
                                });
                            }else {
                                layer.msg("借阅天数超出可借天数限制");
                            }
                        });
                    }else {
                        layer.msg("借阅数量超出可借图书数量限制");
                    }
                    break;
            }
        });

        table.on('tool(returnBookTable)', function(obj){
            var data = obj.data;
            switch(obj.event){
                case 'returnBook':
                    layer.open({
                        type: 1,
                        area: ['700px', '400px'],
                        btn: ['确认', '取消'],
                        shadeClose: true,
                        title: '正在归还:'+data.title,
                        content: $('#returnInfoFrame'),
                        success: function (index, layero){
                            $("#return-userId").val(data.userId);
                            $("#return-bookId").val(data.bookId);
                            $("#return-borrowDate").val(data.borrowDate);
                            $("#return-account").val(data.account);
                            $("#return-username").val(data.username);
                            $("#return-title").val(data.title);
                        },
                        yes: function (index, layero){
                            $.ajax({
                                url:"${pageContext.request.contextPath}/borrow/returnBook.do",
                                data:{
                                    "borrowId" : data.id,
                                    "userId" : $("#return-userId").val(),
                                    "account" : $("#return-account").val(),
                                    "bookId" : $("#return-bookId").val(),
                                    "title" : $("#return-title").val(),
                                    "borrowDate" : $("#return-borrowDate").val(),
                                    "status" : $("#return-status").val(),
                                },
                                type:"post",
                                dataType:"json",
                                success:function (n){
                                    if(n.success){
                                        layer.msg("归还成功（用户账号："+$("#return-account").val()+"，图书名："+$("#return-title").val()+"）");
                                        layer.close(index);
                                        returnBookTableIns.reload();
                                    }else {
                                        layer.msg("归还失败");
                                    }
                                }
                            });
                        },
                        end: function (res) {
                            $("#returnInfoFrame").css("display",'none');
                        }
                    });

                    break;
                case 'renewBook':
                    layer.prompt({
                        formType: 0,
                        value: $("#return-borrowTimeLimit").val(),
                        title: '续订天数',
                    }, function(value, index, elem){
                        if(value <= $("#return-borrowTimeLimit").val()*1){
                            $.ajax({
                                url:"${pageContext.request.contextPath}/borrow/renewBook.do",
                                data:{
                                    "id" : data.id,
                                    "renewDay" : value
                                },
                                type:"post",
                                dataType:"json",
                                success:function (n){
                                    if(n.success){
                                        layer.msg("续订成功（用户账号："+data.account+"，图书名："+data.title+"）");
                                        layer.close(index);
                                        returnBookTableIns.reload();
                                    }else {
                                        layer.msg("续订失败（"+n.msg+"）");
                                    }
                                }
                            });
                        }else {
                            layer.msg("续订天数不可超出可借天数限制");
                        }
                    });
                    break;
            }
        });

    })
    $(function (){
        startTime();
        function startTime() {
            var today = new Date();
            var y = today.getFullYear();
            var M = today.getMonth()+1;
            var d = today.getDate();
            var w = today.getDay();
            var h = today.getHours();
            var m = today.getMinutes();
            var s = today.getSeconds();
            var week=['星期天','星期一','星期二','星期三','星期四','星期五','星期六'];
            // add a zero in front of numbers<10
            m = checkTime(m);
            s = checkTime(s);
            $('#time').html(y+'年'+M+'月'+d+"日 "+h+':'+m+':'+s+' '+week[w]);//可改变格式
            t = setTimeout(startTime, 500);
            function checkTime(i) {
                if (i < 10) {
                    i = "0" + i;
                }
                return i;
            }
        }


    })

    function borrowBook(){
        let account = $("#account").val();
        if(account === ""){
            layer.msg("请输入用户账号");
            return false;
        }
        $.ajax({
            url : '${pageContext.request.contextPath}/user/getUserByAccount.do',
            type : 'get',
            dataType : 'json',
            data : {
                "account":account
            },
            success : function(n) {
                if(n.success){
                    layer.open({
                        type: 1,
                        area: ['1100px', '520px'],
                        shadeClose: true, //点击遮罩关闭
                        title: '修改图书',
                        content: $('#borrowBookFrame'),
                        success: function (index, layero){
                            $("#borrow-userId").val(n.user.id);
                            $("#borrow-account").val(n.user.account);
                            $("#borrow-username").val(n.user.username);
                            $("#borrow-sex").val(n.user.sex);
                            $("#borrow-phone").val(n.user.phone);
                            $("#borrow-borrowBookLimit").val(n.user.borrowBookLimit);
                            $("#borrow-borrowBooks").val(n.user.borrowBooks);
                            $("#borrow-borrowTimeLimit").val(n.user.borrowTimeLimit);
                            layui.use("table",function () {
                                var table = layui.table;
                                table.reload('borrowBookTable', {
                                    where: {
                                        "serialNumber": $("#borrow-bookSerialNumber").val()
                                    }
                                });
                            })
                        },
                        end: function (res) {
                            $("#borrow-bookSerialNumber").val("");
                            $("#borrow-userId").val("");
                            $("#borrow-account").val("");
                            $("#borrow-username").val("");
                            $("#borrow-sex").val("");
                            $("#borrow-phone").val("");
                            $("#borrow-borrowBookLimit").val("");
                            $("#borrow-borrowBooks").val("");
                            $("#borrow-borrowTimeLimit").val("");
                            $("#borrowBookFrame").css("display",'none');
                        }
                    });
                }else {
                    layer.msg("找不到该用户");
                    return false;
                }
            }
        });

    }
    function returnBook(){
        let account = $("#account").val();
        if(account === ""){
            layer.msg("请输入用户账号");
            return false;
        }

        $.ajax({
            url : '${pageContext.request.contextPath}/user/getUserByAccount.do',
            type : 'get',
            dataType : 'json',
            data : {
                "account":account
            },
            success : function(n) {
                if(n.success){
                    layer.open({
                        type: 1,
                        area: ['700px', '350px'],
                        shadeClose: true,
                        title: '用户（账号：'+account+'）在借图书',
                        content: $('#returnBookFrame'),
                        success: function (index, layero){
                            $("#return-borrowTimeLimit").val(n.user.borrowTimeLimit);
                            layui.use("table",function () {
                                var table = layui.table;
                                table.reload('returnBookTable', {
                                    where: {
                                        "account": account
                                    }
                                });
                            })
                        },
                        end: function (res) {
                            $("#returnBookFrame").css("display",'none');
                        }
                    });
                }else {
                    layer.msg("找不到该用户");
                    return false;
                }
            }
        });
    }
</script>
<div style="display:none;" id="borrowBookFrame">
    <div class="layui-row layui-col-space30" style="width: 95%;padding: 20px;margin-right: 0">
        <form class="layui-form layui-form-pane layui-col-md4">
            <input type="hidden" id="borrow-userId">
            <div class="layui-form-item">
                <label class="layui-form-label">账号</label>
                <div class="layui-input-block">
                    <input class="layui-input" id="borrow-account" disabled>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">用户名</label>
                <div class="layui-input-block">
                    <input class="layui-input" id="borrow-username" disabled>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">性别</label>
                <div class="layui-input-block">
                    <input class="layui-input" id="borrow-sex" disabled>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">手机号</label>
                <div class="layui-input-block">
                    <input class="layui-input" id="borrow-phone" disabled>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: 130px;">借书数量限制</label>
                <div class="layui-input-inline" style="width: 125px;">
                    <input class="layui-input" id="borrow-borrowBookLimit" disabled>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: 130px;">已借图书数</label>
                <div class="layui-input-inline" style="width: 125px;">
                    <input class="layui-input" id="borrow-borrowBooks" disabled>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: 130px;">借书时间限制</label>
                <div class="layui-input-inline" style="width: 125px;">
                    <input class="layui-input" id="borrow-borrowTimeLimit" disabled>
                </div>
            </div>
        </form>
        <form class="layui-form layui-form-pane layui-col-md8">
            <div class="layui-form-item">
                <label class="layui-form-label">图书编号</label>
                <div class="layui-input-block">
                    <input class="layui-input" id="borrow-bookSerialNumber" autocomplete="off" placeholder="请输入图书编号">
                </div>
            </div>
            <table class="layui-hide" id="borrowBookTable" lay-skin="line" lay-filter="borrowBookTable"></table>
        </form>
    </div>
</div>
<div style="display:none;" id="returnBookFrame">
    <div class="layui-row" style="padding:5px;">
        <input type="hidden" id="return-borrowTimeLimit">
        <table class="layui-hide" id="returnBookTable" lay-skin="line" lay-filter="returnBookTable"></table>
    </div>
</div>
<div style="display:none;" id="returnInfoFrame">
    <div class="layui-row" style="padding:20px;">
        <form class="layui-form layui-form-pane layui-col-md12">
            <input type="hidden" id="return-userId">
            <input type="hidden" id="return-bookId">
            <input type="hidden" id="return-borrowDate">
            <div class="layui-form-item">
                <label class="layui-form-label">完成情况</label>
                <div class="layui-input-block">
                    <select id="return-status" lay-filter="type">
                        <c:forEach items="${applicationScope.statusList}" var="a">
                            <option value="${a.value}">${a.value}</option>
                        </c:forEach>
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">账号</label>
                <div class="layui-input-block">
                    <input class="layui-input" id="return-account" disabled>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">用户名</label>
                <div class="layui-input-block">
                    <input class="layui-input" id="return-username" disabled>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">图书名</label>
                <div class="layui-input-block">
                    <input class="layui-input" id="return-title" disabled>
                </div>
            </div>
        </form>
    </div>
</div>
</html>